<?php

namespace App\Model;

/**
 * Class Parent_order
 * @package App\Model
 * @User wuqin
 * @Date 2018/4/10 0010
 * @Time 17:56
 */
class Parent_order extends Common
{
    /**
     * @var bool
     */
//    public $timestamps = false;
    /**
     * @var string
     */
    protected $table = "parent_orders";
    /**
     * @var string
     */
    protected $primaryKey = 'parent_order_id';

    /**
     * 方法 : add_parent_order
     * @User wuqin
     * @DateTime 2018-04-10 17:56
     * @param $var
     * @return Parent_order|bool
     */
    public function add_parent_order($var)
    {
        $this->user_id = $var['user_id'];
        $this->trading_stream_id = $var['trading_stream_id'];
        $this->user_address_id = $var['user_address_id'];
        $this->all_price = $var['all_price'];
        $this->state = 0;

        return $this->save() ? $this : false;
    }

    /**
     * 方法 : update_parent_order
     * @User wuqin
     * @DateTime 2018-04-10 17:56
     * @param $var
     * @return Parent_order|bool
     */
    public function update_parent_order($var)
    {
        $this->user_id = $var['user_id'];
        $this->trading_stream_id = $var['trading_stream_id'];
        $this->user_address_id = $var['user_address_id'];
        $this->all_price = $var['all_price'];
        $this->state = $var['state'];

        return $this->save() ? $this : false;
    }

    public function getOrderByUserId($user_id)
    {
        if (empty($user_id))
            return false;

        $where = array(
            array("where", "user_id", "=", $user_id)
        );

        $res = $this->get($where, "*", 0, 0, ["created_at", "desc"]);
        if (empty($res))
            return false;
        else
            return $res;
    }

    public function getOrderByUserIdAndState($user_id, $state)
    {
        if (empty($user_id))
            return false;

        $where = array(
            array("where", "user_id", "=", $user_id),
            array("where", "state", "=", $state)
        );

        $res = $this->get($where, "*", 0, 0, ["created_at", "desc"]);
        if (empty($res))
            return false;
        else
            return $res;
    }

    public function getOrderJoinUserId($user_id)
    {
        if (empty($user_id))
            return false;

        $where = array(
            array("where", "user_id", "=", $user_id)
        );

        $res = $this->get($where, "*", 0, 0, ["created_at", "desc"]);
        if (empty($res))
            return false;
        else
            return $res;
    }

    public function orders()
    {
        return $this->hasMany('App\Model\Order', "parent_order_id");
    }

    public function order()
    {
        return $this->hasMany(Order::class, "parent_order_id");
    }

    public function address()
    {
        return $this->belongsTo(User_address::class, "user_address_id");
    }

    public function user()
    {
        return $this->belongsTo(User::class, "user_id");
    }
}
